<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <div class="search-box">
        <el-form-item label="商品编号/名称" prop="nameOrId">
          <el-input
            v-model="queryParams.nameOrId"
            placeholder="请输入商品编号/名称查询"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryName">
          <el-select v-model="queryParams.categoryId" placeholder="请选择" clearable>
            <el-option
              v-for="list in categorys"
              :key="list.categoryId"
              :label="list.categoryName"
              :value="list.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brandName">
          <el-select v-model="queryParams.brandId" placeholder="请选择" clearable>
            <el-option
              v-for="list in brands"
              :key="list.brandId"
              :label="list.brandName"
              :value="list.brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在仓库" prop="warehouseName">
          <el-select v-model="queryParams.warehouseId" placeholder="请选择" clearable>
            <el-option
              v-for="list in warehouses"
              :key="list.warehouseId"
              :label="list.warehouseName"
              :value="list.warehouseId"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="search-box">
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option
              v-for="dict in dict.type.erp_enable_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间">
          <el-date-picker
            v-model="queryParams.value2"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <!--按钮组-->
    <div class="search-btn">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
    </div>
    <!--数据展示区-->
    <div class="data-box">
      <el-table v-loading="loading" :data="productList">
        <el-table-column type="index" label="序号" align="center" width="10"/>
        <el-table-column label="商品编号" align="center" prop="productId"/>
        <el-table-column label="商品图片" align="center" prop="imageUrl">
          <template slot-scope="scope">
            <el-image :src="scope.row.imageUrl" style="width: 100px; height: 100px" fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="productName"/>
        <el-table-column label="商品分类" align="center" prop="categoryName"/>
        <el-table-column label="商品品牌" align="center" prop="brandName"/>
        <el-table-column label="商品单位" align="center" prop="unitName"/>
        <el-table-column label="所在仓库" align="center" prop="warehouseName"/>
        <el-table-column label="建议采购价" align="center" prop="suggestedPrice"/>
        <el-table-column label="建议零售价" align="center" prop="suggestedRetailPrice"/>
        <el-table-column label="创建时间" align="center" prop="creationTime"/>
        <el-table-column label="修改时间" align="center" prop="modifyTime"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.erp_enable_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:post:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDisable(scope.row)"
              v-hasPermi="['system:post:remove']"
            >{{ scope.row.status === 'Y' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="check(scope.row)"
              v-hasPermi="['system:post:edit']"
            >查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <div class="pagination-box">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!--添加/修改弹窗-->
    <div class="dialog-box">
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="商品名称" prop="productName">
            <el-input v-model="form.productName" placeholder="请输入商品名称"/>
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryName">
            <el-select v-model="form.categoryId" placeholder="请选择商品分类">
              <el-option
                v-for="category in categorys"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品品牌" prop="brandName">
            <el-select v-model="form.brandId" placeholder="请选择商品品牌">
              <el-option
                v-for="list in brands"
                :key="list.brandId"
                :label="list.brandName"
                :value="list.brandId"
              />

            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" prop="unitName">
            <el-select v-model="form.unitId" placeholder="请选择商品单位">
              <el-option
                v-for="unit in units"
                :key="unit.unitId"
                :label="unit.unitName"
                :value="unit.unitId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所在仓库" prop="warehouseName">
            <el-select v-model="form.warehouseId" placeholder="请选择所在仓库" clearable>
              <el-option
                v-for="list in warehouses"
                :key="list.warehouseId"
                :label="list.warehouseName"
                :value="list.warehouseId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="建议采购价" prop="suggestedPrice">
            <el-input v-model="form.suggestedPrice" placeholder="请输入建议采购价"/>
          </el-form-item>
          <el-form-item label="建议零售价" prop="suggestedRetailPrice">
            <el-input v-model="form.suggestedRetailPrice" placeholder="请输入建议零售价"/>
          </el-form-item>
          <el-form-item label="详情链接" prop="externalLink">
            <el-input v-model="form.externalLink" placeholder="请输入外链"/>
          </el-form-item>
          <el-form-item label="商品图片" prop="file">
            <!--将图片存入from.file-->
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/erp/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" width="200px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listProduct,
  listCategory,
  listBrand,
  listUnit,
  updateProduct,
  addProduct,
  deleteOldImg,
  listWarehouse
} from "@/api/erp/product";
import warehouse from "@/views/erp/warehouse/index.vue";

export default {
  name: "product",
  dicts: ['erp_enable_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层是否显示
      open: false,

      // 图片本机内存地址
      imageUrl: '',
      // 弹出层标题
      title: '',
      // 总条数
      total: 0,
      // 商品列表
      productList: [],
      // 商品分类列表
      categorys: [],
      // 商品品牌列表
      brands: [],
      // 商品单位列表
      units: [],
      // 仓库列表
      warehouses: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          {required: true, message: '商品名称不能为空', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: '商品分类不能为空', trigger: 'blur'}
        ],
        brandId: [
          {required: true, message: '商品品牌不能为空', trigger: 'blur'}
        ],
        unitId: [
          {required: true, message: '商品单位不能为空', trigger: 'blur'}
        ],
        warehouseId: [
          {required: true, message: '所在仓库不能为空', trigger: 'blur'}
        ],
        suggestedPrice: [
          {required: true, message: '建议采购价不能为空', trigger: 'blur'}
        ],
        suggestedRetailPrice: [
          {required: true, message: '建议零售价不能为空', trigger: 'blur'}
        ]
      },
      // 查询参数
      queryParams: {
        nameOrId: undefined,
        categoryId: undefined,
        brandId: undefined,
        warehouseId: undefined,
        status: undefined,
        value1: [],
        value2: [],
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  // 页面加载时执行
  created() {
    // 调用查询方法
    this.getList()
    this.getCategoryList()
    this.getBrandList()
    this.getUnitList()
    this.getWarehouseList()

  },
  methods: {
    /** 查询商品品牌列表 */
    getList() {
      // 遮罩层开启
      this.loading = true
      // 调用查询方法
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        // 遮罩层关闭
        this.loading = false
      })
    },
    // 文件上传成功时的钩子
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // 删除旧图片
      if (this.title === '修改商品') {
        deleteOldImg(this.form.imageUrl).then(response => {
          console.log(response)
        })
      }
      this.form.imageUrl = res.msg
    },
    // 文件上传之前的钩子
    beforeAvatarUpload(file) {
      // 限定数据只能是图片
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 查询商品分类列表
    getCategoryList() {
      // 调用查询方法
      listCategory().then(response => {
        this.categorys = response.rows
      })
    },
    // 查询商品品牌列表
    getBrandList() {
      // 调用查询方法
      listBrand().then(response => {
        this.brands = response.rows
      })
    },
    // 查询商品单位列表
    getUnitList() {
      // 调用查询方法
      listUnit().then(response => {
        this.units = response.rows
      })
    },
    // 查询商品仓库列表
    getWarehouseList() {
      // 调用查询方法
      listWarehouse().then(response => {
        this.warehouses = response.rows
      })
    },
    // 修改商品信息弹窗方法
    handleUpdate(row) {
      console.log(row)
      // 打开弹窗
      this.open = true
      // 设置标题
      this.title = '修改商品'
      // 清空表单
      this.reset()
      // 赋值
      this.form = row
      this.imageUrl = this.form.imageUrl
    },
    // 启用禁用方法
    handleDisable(row) {
      if (row.status === 'Y') {
        this.$modal.confirm('是否确认禁用该商品？').then(function () {
          row.status = 'N'
          // 调用更新方法
          return updateProduct(row)
        }).catch(() => {
          console.log("禁用方法")
        })
      } else {
        this.$modal.confirm('是否确认启用该商品？').then(function () {
          row.status = 'Y'
          // 调用更新方法
          return updateProduct(row)
        }).catch(() => {
          console.log("启用方法")
        })
      }

    },
    // 查询方法
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置方法
    resetQuery() {
      // 清空查询参数
      this.resetForm('queryForm')
      this.queryParams.brandId = undefined
      this.queryParams.categoryId = undefined
      this.queryParams.status = undefined
      // 重新查询
      this.handleQuery()
    },
    // 弹出层保存按钮方法
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === '添加商品') {
            if (this.form.file) {
            }
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          } else {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          }
        }
      })

    },
    // 弹出层取消按钮方法
    cancel() {
      // 关闭弹出层
      this.open = false
      // 清空表单数据
      this.reset()
    },
    // 新增方法
    handleAdd() {
      // 打开弹窗
      this.open = true
      // 设置标题
      this.title = '添加商品'
      // 清空表单
      this.reset()
      this.imageUrl = ''
    },
    // 查看方法
    check(data) {
      // 跳转到外链
      window.open(data.externalLink)
    },
    // 重置表单方法
    reset() {
      this.form = {
        productName: undefined,
        categoryId: undefined,
        brandId: undefined,
        unitId: undefined,
        suggestedPrice: undefined,
        suggestedRetailPrice: undefined,
        imageUrl: undefined,
        warehouseId: undefined,
        status: null
      }
      this.resetForm("form")
    },
  }
}
</script>

<style scoped lang="scss">

</style>
